package com.hl.mytools.ui

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson.JSON
import com.hl.lib.base.BaseViewModel
import com.hl.lib.const.DateFormats
import com.hl.lib.utils.net.HttpUtil
import com.hl.mytools.data.ConstData
import com.hl.mytools.data.Urls
import com.hl.mytools.database.FundInfo
import com.hl.mytools.entity.FundPriceInfo
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONException
import org.json.JSONObject
import java.time.LocalDate
import kotlin.math.min

class MainActivityViewModel : BaseViewModel() {
    companion object {
        private val TAG = MainActivityViewModel::class.simpleName
    }

    val state: MutableLiveData<Boolean> = MutableLiveData<Boolean>(false)
    val fundListLiveData = MutableLiveData<MutableList<FundInfo>>()
    val fundList = mutableListOf<FundInfo>()
    val soredFundList = mutableListOf<FundInfo>()
    val highFundList = mutableListOf<FundInfo>()
    val lowFundList = mutableListOf<FundInfo>()
    val increaseFundList = mutableListOf<FundInfo>()
    val decreaseFundList = mutableListOf<FundInfo>()
    val percent15FundList = mutableListOf<FundInfo>()

    override fun start() {

    }


//    fun queryFoundInfo() {
//        viewModelScope.launch {
//            ConstData.fundList.forEach {
//                launch(Dispatchers.IO) {
//                    val url = Urls.fund_query_url + it.code
//                    val response = HttpUtil.get(url)
//                    Log.e(TAG, "queryFoundInfo: $url :: $response")
//                    parseResult(it, response)
//                    Log.e(TAG, "queryFoundInfo: ${JSON.toJSONString(it)}")
//                    fundList.add(it)
//                }
//            }
//        }
//        parseFunds()
//        Log.e(TAG, "queryFoundInfo: 通知数据变换")
//        state.postValue(true)
//    }

    fun queryFoundInfo() {
        fundList.clear()
        viewModelScope.launch(Dispatchers.IO) {
            // 控制并发数量，例如最多并发10个请求
            val maxConcurrent = 10
            val allTasks = mutableListOf<Deferred<Boolean>>()

            ConstData.fundList.chunked(maxConcurrent).forEach { chunk ->
                chunk.forEach { fund ->
                    allTasks.add(async {
                        val url = Urls.fund_query_url + fund.code
                        val response = HttpUtil.get(url)
                        Log.e(TAG, "queryFoundInfo: $url :: $response")
                        parseResult(fund, response)
                        Log.e(TAG, "queryFoundInfo: ${JSON.toJSONString(fund)}")
                        // 保证线程安全的添加到集合
                        withContext(Dispatchers.Main) {
                            fundList.add(fund)
                        }
                    })
                }
            }

            // 等待所有请求完成
            allTasks.awaitAll()

            withContext(Dispatchers.Main) {
                parseFunds()
                Log.e(TAG, "queryFoundInfo: 通知数据变换")
                state.postValue(true)
            }
        }
    }


    private fun parseFunds() {
        highFundList.clear()
        lowFundList.clear()
        increaseFundList.clear()
        decreaseFundList.clear()
        percent15FundList.clear()
        soredFundList.clear()
        Log.e(TAG, "parseFunds: 解析基金")
        fundList.forEach {
            val high = it.fundPriceInfoList?.maxByOrNull { it.jjjz }
            val low = it.fundPriceInfoList?.minByOrNull { it.jjjz }
            Log.e(TAG, "queryFoundInfo high = : ${JSON.toJSONString(high)}")
            Log.e(TAG, "queryFoundInfo low = : ${JSON.toJSONString(low)}")
            val yesterday = DateFormats.normalData.format(LocalDate.now().minusDays(1))
            // 创新高
            if (high?.fbrq == it.fundPriceInfoList?.get(0)?.fbrq) {
                it.adviceKind = "卖"
                it.adviceReason = "创新高"
                highFundList.add(it)
            }

            //创新低
            if (low?.fbrq == it.fundPriceInfoList?.get(0)?.fbrq) {
                it.adviceKind = "买"
                it.adviceReason = "创新低"
                lowFundList.add(it)
            }

            it.fundPriceInfoList?.let { list ->
                var count: Int = 0

                for (i in 0 until list.size - 1) {
                    if (list[i].jjjz.toDouble() >= list[i + 1].jjjz?.toDouble()!!) {
                        count++
                    } else {
                        break
                    }
                }

                if (count >= 3) {
                    it.adviceKind = "卖"
                    it.adviceReason = "连涨 $count 天"
                    increaseFundList.add(it)
                }

                count = 0

                for (i in 0 until list.size - 1) {
                    if (list[i].jjjz.toDouble() < list[i + 1].jjjz?.toDouble()!!) {
                        count++
                    } else {
                        break
                    }
                }

                if (count >= 3) {
                    it.adviceKind = "卖"
                    it.adviceReason = "连跌 $count 天"
                    increaseFundList.add(it)
                }

                val lowPrice = low?.ljjz?.toDouble()!!
                val newPrice = list[0].jjjz?.toDouble()!!
                if (newPrice / lowPrice >= 1.15) {
                    it.adviceKind = "卖"
                    it.adviceReason = "涨超15%"
                    percent15FundList.add(it)
                }
            }
        }

        //买
        soredFundList.addAll(highFundList)
        Log.e(TAG, "parseFunds: ${JSON.toJSONString(increaseFundList)}")

        soredFundList.addAll(increaseFundList)
        soredFundList.addAll(percent15FundList)

        //卖
        soredFundList.addAll(lowFundList)
        soredFundList.addAll(decreaseFundList)


    }


    private fun parseResult(fundInfo: FundInfo?, result: String) {
        val start = result.indexOf('{')
        val end = result.lastIndexOf('}')
        val dataResult = result.substring(start, end + 1)
        try {
            val allDataObject = JSONObject(dataResult)
            val resultObject = allDataObject.getJSONObject("result")
            val outDataObject = resultObject.getJSONObject("data")
            val inDataObjectArray = outDataObject.getJSONArray("data")
            val iSize = inDataObjectArray.length()
            val fundPriceInfoList: MutableList<FundPriceInfo> = ArrayList()
            var fundPriceInfo: FundPriceInfo
            Log.w(TAG, "Size:$iSize")
            val finalSize = min(iSize.toDouble(), iSize.toDouble()).toInt()
            for (i in 0 until finalSize) {
                val jsonObject = inDataObjectArray.getJSONObject(i)
                var rq = jsonObject.getString("fbrq")
                rq = rq.substring(0, rq.indexOf(" "))
                fundPriceInfo = FundPriceInfo(
                    rq,
                    jsonObject.getString("jjjz"),
                    jsonObject.getString("ljjz")
                )
                fundPriceInfoList.add(fundPriceInfo)
                fundInfo!!.fundPriceInfoList = fundPriceInfoList
            }
        } catch (e: JSONException) {
            Log.e(TAG, "e = " + e.message)
        }
    }


}